package leetcode.problems.P145二叉树的后序遍历;

import java.util.*;

public class PostorderTraversal {
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

// 递归
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ans = new LinkedList<>();
        traversal(root, ans);
        return ans;
    }

    private void traversal(TreeNode root, List<Integer> list) {
        if (root != null) {
            traversal(root.left, list);
            traversal(root.right, list);
            list.add(root.val);
        }
    }
}

// 迭代
class Solution2 {
    public List<Integer> postorderTraversal(TreeNode root) {
        if (root == null) return Collections.EMPTY_LIST;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode prev = null;
        List<Integer> ans = new LinkedList<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();// 从栈里取出的节点都不考虑遍历其左子树，只判断其右子树是否存在及是否已被遍历
            if (root.right == null || prev == root.right) {
                ans.add(root.val);
                prev = root;
                root = null;
            } else {// 存在且未被遍历
                stack.push(root);
                root = root.right;
            }
        }
        return ans;
    }
}